import * as React from "react";
import { Modal, Input, Select, Form, InputNumber } from "antd";
import {
  findParamsByProtocolId,
  updateProtocolParaVal,
} from "../../../ServeApi";
import { AjaxData } from "../../../../../../data/interface/publicInterface";
export interface updateItemDataProps {
  visible: boolean;
  attr: any;
  onOk: (data: any) => any;
  onCancel: (data: any) => any;
}

export interface updateItemDataState {
  visible: boolean;
}
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 16 },
  },
};
class updateItemData extends React.Component<
  updateItemDataProps,
  updateItemDataState
> {
  private dataSouce: any = [];
  formRef: any = null;
  state = { visible: false };
  render() {
    let { visible } = this.state;
    return (
      <>
        <Modal
          title="设置默认参数"
          visible={visible}
          okText="确认"
          cancelText="取消"
          onOk={() => {
            this.handleOk();
          }}
          onCancel={() => {
            this.handleCancel();
          }}
        >
          <Form {...formItemLayout} ref={(el) => (this.formRef = el)}>
            {this.dataSouce.length ? (
              this.dataSouce.map((item: any, index: number) => {
                return this.createForm(item);
              })
            ) : (
              <div>项目协议未设默认参数，请先设置默认参数！</div>
            )}
          </Form>
        </Modal>
      </>
    );
  }
  shouldComponentUpdate(
    newProps: updateItemDataProps,
    newState: updateItemDataState
  ) {
    if (newProps.visible !== this.props.visible) {
      this.setState({ visible: newProps.visible });
      this.findItemData({ protocolId: newProps.attr.id });
      this.forceUpdate();
    }
    return true;
  }
  /**数据请求 */
  //修改协议参数
  async updateItemData(pream: any) {
    let res: any = await updateProtocolParaVal(JSON.stringify(pream)).catch(
      (err) => {
        console.log(err);
      }
    );
    let json: AjaxData = res;
    if (json.success) {
      this.props.onOk({ visible: false });
    }
  }
  //查看协议参数
  async findItemData(pream: any) {
    let res: any = await findParamsByProtocolId(JSON.stringify(pream)).catch(
      (err) => {
        console.log(err);
      }
    );
    let json: AjaxData = res;
    let initValJson = {};
    if (json.success) {
      let data1: any[] = json.data;
      data1.forEach((item) => {
        initValJson[item["protocalNo"]] = item["defaultValue"];
      });
      const container: any = (this.formRef as any) as HTMLDivElement;
      container.setFieldsValue({ ...initValJson });
      this.dataSouce = json.data;
      this.forceUpdate();
    }
  }
  /**操作 */
  handleOk() {
    const container: any = (this.formRef as any) as HTMLDivElement;
    container
      .validateFields()
      .then((res) => {
        //输出修改后的参数
        let pream = { defaultVal: res, protocolId: this.props.attr.id };
        this.updateItemData(pream);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  handleCancel() {
    this.dataSouce = [];
    this.forceUpdate();
    setTimeout(() => {
      this.props.onCancel({ visible: false });
    });
  }
  /*方法 */
  //清除新增弹窗
  clearAddModal() {
    this.forceUpdate();
  }
  /**生成表单 */
  createForm = (row) => {
    if (row === undefined || row === {} || row === "") {
      return;
    }
    if (row["protocalNo"] === "bjxh" || row["protocalNo"] === "cldh") {
      //测量点和表计序号特殊处理
      return this.createOtherIntInput(row, row["protocalNo"]);
    } else {
      // 数据类型(0：整型，1：枚举，2：浮点；3：日期；4：字符；5：十六进制)
      switch (row["dataType"]) {
        case "0":
          return this.createIntInput(row);
        case "1":
          return this.createEnumSelect(row);
        // case "2":
        //     return createFloatInput(row);
        // case "3":
        //     return  createDateInput(row);
        case "4":
          return this.createStrInput(row);
        // case "5":
        //     return  createHexInput(row);
        default:
          return this.createStrInput(row);
      }
    }
  };
  // 4：字符
  createStrInput = (row) => {
    return (
      <Form.Item
        key={row["id"]}
        label={row["protocalName"]}
        name={row["protocalNo"]}
        style={{ height: "25px", width: "90%" }}
      >
        <Input name={row["protocalNo"]} style={{ width: "90%" }} />
      </Form.Item>
    );
  };
  // 1:枚举
  createEnumSelect = (row) => {
    const arr = row["enumList"].split("@");
    let arrList = [{}];
    for (let idx in arr) {
      let item = arr[idx];
      const arrTemp = item.split(",");
      let json = {};
      json["name"] = arrTemp[0];
      json["value"] = arrTemp[1];
      arrList.push(json);
    }
    arrList.shift(); //去掉第一个空元素
    return (
      <Form.Item
        key={row["id"]}
        label={row["protocalName"]}
        style={{ height: "25px", width: "90%" }}
        name={row["protocalNo"]}
      >
        <Select key={row["id"]} style={{ width: "90%" }}>
          {arrList.length &&
            arrList.map((item, index) => {
              return (
                <Select.Option key={index} value={item["value"]}>
                  {item["name"]}
                </Select.Option>
              );
            })}
        </Select>
      </Form.Item>
    );
  };

  // 0:整型表单
  createIntInput = (row) => {
    return (
      <Form.Item
        key={row["id"]}
        label={row["protocalName"]}
        name={row["protocalNo"]}
        style={{ height: "25px", width: "90%" }}
      >
        <InputNumber name={row["protocalNo"]} style={{ width: "90%" }} />
      </Form.Item>
    );
  };
  createOtherIntInput = (row, type) => {
    return (
      <Form.Item
        key={row["id"]}
        label={row["protocalName"]}
        name={type}
        style={{ height: "25px", width: "90%" }}
      >
        <InputNumber
          name={type}
          min={1}
          max={1024}
          style={{ width: "90%" }}
          onChange={(value) => {
            const container: any = (this.formRef as any) as HTMLDivElement;
            if (type === "cldh") {
              container.setFieldsValue({ bjxh: value });
            } else {
              container.setFieldsValue({ cldh: value });
            }
          }}
        />
      </Form.Item>
    );
  };
}

export default updateItemData;
